const {readBody} = require('./utils');
const {parse} = require('es-module-lexer'); // 解析import语法的
const MagicString = require('magic-string');

function rewriteImports(source) {
  //console.log('source:',source);
  let imports = parse(source)[0]/*索引为0是普通的import,索引为1的是动态import*/;
  // console.log('imports:',imports)
/*
[ { s: 27, e: 30, ss: 0, se: 31, d: -1 },
  { s: 49, e: 58, ss: 32, se: 59, d: -1 } ]
* */
  let magicString = new MagicString(source);
  //对import语法进行拦截
  if(imports.length){
    for (let i = 0; i < imports.length; ++i) {
      let {s,e} = imports[i];
      let id = source.substring(s, e);
      console.log('id:', id);

      // 以/或则.开头的不需要重写
      if(/^[^\/\.]/.test(id)){
        id = `/@modules/${id}`;
        magicString.overwrite(s, e, id);
      }
    }
  }
  return magicString.toString();
}

function moduleRewritePlugin({app, root}) { // 启动项目时的根路径
  app.use(async (ctx, next) => {
    await next();

    // 在这里完善了自己的逻辑 洋葱模型
    if (ctx.body && ctx.response.is('js')) {
      const content = await readBody(ctx.body);
      const result = rewriteImports(content);
      ctx.body = result;
    }
  });
}

exports.moduleRewritePlugin = moduleRewritePlugin;
